import { useState, useCallback, useRef } from "react";
import i18n from "i18n-js";
import { observer } from 'mobx-react';
import homesModel from '@/models/homes';
import deviceListModel from '@/models/deviceList';
import PageContainer from "@/components/PageContainer";
import { DynamicColors, GStyleSheet } from "@/utils/DarkMode";
import { View } from "@tarojs/components";
import { GButton } from "@/components/GButton";
import FlexScrollView from '@/components/FlexScrollView';
import { isSameDevice } from '@/utils';
import Toast from "@/utils/Toast";
import { backToHome } from '../models/configTool';
import configWifiModel from '../models/configWifi';
import DeviceItem from './DeviceItem';

const dstyles = GStyleSheet.create({
  container: {
    width: "100%",
    height: "100%",
    background: DynamicColors.normalBackgroundColor,
    padding: "32rpx",
    boxSizing: "border-box",
    borderTop: "1rpx solid rgba(0,0,0,0.1)",
    flexDirection: 'column',
    justifyContent: 'space-between'
  },
  title: {
    fontSize: 18,
    color: DynamicColors.normalTextColor,
    textAlign: "center",
    marginBottom: "40rpx",
  },
  desc: {
    width: "100%",
    padding: "40rpx 40rpx",
    boxSizing: "border-box",
    backgroundColor: DynamicColors.screenBackgroundGaryColor,
    borderRadius: 10,
    flex: 1,
    height: '100%'
  },
});


const ConfigSuccessPage = () => {
  const styles = dstyles.useDynamicStyle();
  console.log('configWifiModel', configWifiModel.devices.length);
  const listRef = useRef(configWifiModel.devices);
  const haveChangeName = useRef(false);
  const [list, setList] = useState(listRef.current);

  const goBack = useCallback(async () => {
    console.log('device', list);
    if (haveChangeName.current) {
      Toast.loading('');
      for (let index = 0; index < list.length; index++) {
        const device = list[index];
        await homesModel.renameDevice({ device, name: device.name, refreshHomes: false });
      }
      Toast.hideLoading()
      backToHome();
      deviceListModel.getDeviceList();
    } else {
      backToHome();
    }
  }, [list]);

  const changeName = useCallback(({ device, name }: { device: IDevice, name: string }) => {
    haveChangeName.current = true;
    const index = list.findIndex(i => isSameDevice(i, device));
    if (index > -1) {
      list.splice(index, 1, { ...device, name });
      setList([...list]);
    }
  }, [list])

  return (
    <PageContainer title={i18n.t('ADD_FINISH')}>
      <View style={styles.container} className='centerFlex'>
        <View style={styles.desc} className='centerFlex'>
          <FlexScrollView id='successDeviceList'>
            {list.map((device) => {
              return (<DeviceItem key={device.did} device={device} onChangeName={changeName} />)
            })}
          </FlexScrollView>
        </View>
        <GButton style={{ marginTop: 40 }} text={i18n.t('COMPLETED')} onPress={goBack} />
      </View>
    </PageContainer>
  );
};

export default observer(ConfigSuccessPage);
